package com.yuyu.excel.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuyu.excel.entity.User;
import com.yuyu.excel.mapper.UserMapper;
import com.yuyu.excel.service.excel.DataRecordDisruptor;
import com.yuyu.excel.utils.ExcelUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;


@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Resource
    private DataRecordDisruptor<User> disruptor;

    @SneakyThrows
    public void importExcel(MultipartFile file) {
        EasyExcel.read(file.getInputStream(), User.class, new ExcelListener(disruptor)).sheet().doRead();
    }

    @SneakyThrows
    public void downloadExcelModel(HttpServletResponse resp) {
        ExcelUtil.writeExcel(resp, null, "Excel导入模版", "sheet1", User.class);
    }

    @SneakyThrows
    public void exportExcel(HttpServletResponse resp) {
        ExcelUtil.writeExcel(resp, list(), "Excel导出", "sheet1", User.class);
    }

    private static class ExcelListener extends AnalysisEventListener<User> {

        private final DataRecordDisruptor<User> disruptor;

        private final List<User> batch = new ArrayList<>();

        public ExcelListener(DataRecordDisruptor<User> disruptor) {
            this.disruptor = disruptor;
        }

        @Override
        public void invoke(User data, AnalysisContext analysisContext) {
            batch.add(data);
            if (batch.size() >= 100000) {
                List<User> users = BeanUtil.copyToList(batch, User.class);
                disruptor.publish(users);
                batch.clear();
            }
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            if (CollUtil.isNotEmpty(batch)) {
                disruptor.publish(batch);
            }
        }
    }

}
